﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// B = bwboundaries(BW) traces the exterior boundaries of objects, 
    /// as well as boundaries of holes inside these objects, in the binary image BW. 
    /// bwboundaries also descends into the outermost objects (parents) and traces their children
    /// (objects completely enclosed by the parents). 
    /// BW must be a binary image where nonzero pixels belong to an object and 0 pixels constitute the background.
    /// The following figure illustrates these components.
    /// 
    /// </summary>
    public class bwboundaries : BaseForeBackgroundColorFilter
    {
        protected BlackWhitePerimeter filter = new BlackWhitePerimeter();

        /// <summary>
        /// Initializes a new instance of the <see cref="bwboundaries"/> class.
        /// </summary>
        public bwboundaries()
        {
            this.m_ColorForeground = Definitions.Green;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="bwboundaries"/> class.
        /// </summary>
        /// <param name="_bwboundaries">The _bwboundaries.</param>
        internal bwboundaries(bwboundaries _bwboundaries)
        {
            this.m_ColorForeground = _bwboundaries.m_ColorForeground;
            this.m_ColorBackground = _bwboundaries.m_ColorBackground;
        }

        /// <summary>
        /// Execute this Filter
        /// A Debug Statement is written if a concrete Filter is called
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmapCloned = (UnsafeBitmap)_bitmap.Clone();

            filter.Execute(bitmapCloned);

            int x = 0;
            int y = 0;
            int nWidth = _bitmap.Width;
            int nHeight = _bitmap.Height;
            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    _bitmap.SetPixel(x, y,
                        bitmapCloned.GetPixel(x, y) == filter.Foreground ? m_ColorForeground : m_ColorBackground);
                }
            }
            return _bitmap;
        }

        /// <summary>
        /// This is used to clone a filter, each filter must implement it's own clone functionality
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new bwboundaries(this);
        }
    }
}
